const db = uniCloud.database()
module.exports = {
	_before: function() {},
	defaultAddress(userId) {
		return db.collection('user-address').limit(1).where({
			user_id: userId,
			is_default: true
		}).get()
	},
	async getCoupon(user_id,coupon_id){
		let userGet= await db.collection('uni-id-users').doc(user_id).get();
		if(userGet.data.length>0){
			let couponGet=await db.collection('coupon').where({
				_id:coupon_id,
				available:dbCmd.gt(0)
				}).get();
			if(couponGet.data.length>0){
				
			}else{
				return{
					code:1,
					errMsg:'没有这个优惠卷'
				}
			}
		}else{
			return{
				code:1,
				errMsg:'没有该用户'
			}
		}
	},
	async money(userId) {
		let resUser = await db.collection('uni-id-users').limit(1).where({
			_id: userId
		}).get();
		return {
			affectedDocs: resUser.affectedDocs,
			data: {
				money: resUser.data[0].money
			}
		}
	},
	async addressList(userId) {
		let list = await db.collection('user-address').where({
			user_id: userId
		}).get();
		list.defaultId = "";
		for (let i = 0; i < list.data.length; i++) {
			const elem = list.data[i];
			list.data[i].id = elem._id
			list.data[i].tel = elem.mobile
			list.data[i].address = elem.formatted_address
			list.data[i].isDefault = elem.is_default
			if (elem.is_default) {
				list.defaultId = elem._id
			}
		}
		return list
	},
	async setAddressDefault(Id, userId) {
		let adrDB = db.collection('user-address')
		// 大家自己完成更新默认地址
		// ERROR userId->user_id
		let update = await adrDB.where({
			user_id: userId
		}).update({
			is_default: false
		})
		let def = await adrDB.where({
			user_id: userId,
			_id: Id
		}).update({
			is_default: true
		})
		return def;
	}

}
